package com.lgl.aspect;

import com.alibaba.fastjson.JSON;
import com.lgl.annotation.SysLog;
import com.qiniu.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Component
@Aspect
public class LogAspect {
    //    定义切点
    @Pointcut("@annotation(com.lgl.annotation.SysLog)")
    public void pt() {
    }

    @Around("pt()")
    public Object printLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object proceed;
        try {
            logBefore(proceedingJoinPoint);
            proceed = proceedingJoinPoint.proceed();
            logAfter(proceed);
        } finally {
            // 结束后换行
            log.info("=======End=======" + System.lineSeparator());
        }
        return proceed;

    }

    private void logBefore(ProceedingJoinPoint proceedingJoinPoint) {
        SysLog sysLog = getSysLog(proceedingJoinPoint);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL            : {}",requestAttributes.getRequest().getRequestURI());
        // 打印描述信息
        log.info("BusinessName   : {}",sysLog.businessName() );
        // 打印 Http method
        log.info("HTTP Method    : {}",requestAttributes.getRequest().getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", proceedingJoinPoint.getSignature().getDeclaringTypeName(),((MethodSignature) proceedingJoinPoint.getSignature()).getName() );
        // 打印请求的 IP
        log.info("IP             : {}",requestAttributes.getRequest().getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(proceedingJoinPoint.getArgs()));
    }

    private SysLog getSysLog(ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
       return signature.getMethod().getAnnotation(SysLog.class);
    }

    private void logAfter(Object a) {
        log.info("Response       : {}",JSON.toJSONString(a));
    }
}
